import bcrypt from "bcryptjs";
import type { NextAuthConfig } from "next-auth";
import CredentialsProvider from "next-auth/providers/credentials";
import { getUserByEmail } from "@/data/user";
import { CustomUser } from "./types/user";

export default {
  providers: [
    CredentialsProvider({
      name: "Credentials",
      credentials: {
        email: { label: "Email", type: "text" },
        password: { label: "Password", type: "password" },
      },
      authorize: async (
        credentials: Partial<Record<"email" | "password", unknown>>,
      ): Promise<CustomUser | null> => {
        let user = null;
        const email = credentials.email as string;
        const password = credentials.password as string;
        if (email === "") return null;
        if (password === "") return null;
        try {
          user = await getUserByEmail(email);
        } catch (err) {
          return user;
        }
        if (!user || !user.password) return null;
        const passwordsMatch = await bcrypt.compare(password, user.password);
        if (passwordsMatch) {
          return {
            id: user.id,
            name: user.name,
            email: user.email,
            role: user.role,
            image: user.image,
          };
        }
        return null;
      },
    }),
  ],
} satisfies NextAuthConfig;
